import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/base/base_app.dart';
import 'dart:async';

import 'package:intl/intl.dart';
//静态路由配置
void main() => runApp(BaseApp(homeWidget: Exam205HomePage()));

class Exam205HomePage extends StatefulWidget {
  @override
  State<Exam205HomePage> createState() => _TestABPageState();
}

///代码清单7-5-1
///本小节源码在 lib/code7/code706_StreamTimer_page.dart文件中
class _TestABPageState extends State<Exam205HomePage> {

  ///使用单订阅流即可
  final StreamController<String> _streamController = StreamController();
  ///计时器
  Timer ?_timer;

  @override
  void initState() {
    super.initState();
    ///间隔1秒执行时间
    _timer= Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      ///获取当前的时间
      DateTime dateTime= DateTime.now();
      ///格式化时间
      String formatTime = DateFormat("HH:mm:ss").format(dateTime);
      ///流数据更新
      _streamController.add(formatTime);
    });

  }

  @override
  void dispose() {
    super.dispose();
    ///关闭
    _streamController.close();
    if(_timer!=null&&_timer!.isActive) {
      ///取消计时器
      _timer!.cancel();
      _timer=null;
    }
  }

  ///代码清单7-5-1
  @override
  Widget build(BuildContext context) {
    ///页面主体脚手架
    return Scaffold(
      body:Center(child: buildStreamBuilder(),),
    );
  }

  ///代码清单1-1
  /// 监听Stream，每次值改变的时候，更新Text中的内容
  StreamBuilder<String> buildStreamBuilder() {
    return StreamBuilder<String>(
      ///绑定stream
      stream: _streamController.stream,
      ///默认的数据
      initialData: "00:00:00",
      ///构建绑定数据的UI
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        ///snapshot.data 就是传递的数据对象
        return Text(
          '当前时间  ${snapshot.data} ',
          style: const TextStyle(fontSize: 22, color: Colors.blue),
        );
      },
    );
  }
}

